package cn.bxshey.serviceModule.service.impl;

import cn.bxshey.configModule.ws.SessionBean;
import cn.bxshey.configModule.ws.WsHandler;
import cn.bxshey.serviceModule.service.WebSocketService;
import cn.bxshey.strategyModule.message.MessageStrategy;
import cn.bxshey.strategyModule.message.MessageStrategyFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.PingMessage;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

/**
 * @作者：不想说话而已
 * @Date：2024/3/9 19:39
 */

@Service
public class WebSocketServiceImpl implements WebSocketService {

    @Resource
    WsHandler wsHandler;


    //定时心跳发送，每3分钟发送一次
    @Scheduled(fixedRate = 18000)
    public void isOnline() throws IOException {
        //获取socket的map集合
        Map<String, SessionBean> sessionBeanMap = wsHandler.getSessionBeanMap();
        for (String key : wsHandler.getSessionBeanMap().keySet()) {
            sessionBeanMap.get(key).getSession().sendMessage(new PingMessage(ByteBuffer.wrap(new byte[0])));
        }
        System.err.println("定时发送中");
    }

    //发送文本信息包括JSON格式的信息
    public void sendMsg(){
        //获取socket的map集合
//        Map<String, SessionBean> sessionBeanMap = wsHandler.getSessionBeanMap();
//        for (String key : wsHandler.getSessionBeanMap().keySet()) {
//            sessionBeanMap.get(key).getSession().sendMessage(new PingMessage(ByteBuffer.wrap(new byte[0])));
//        }
        MessageStrategy messageStrategy = MessageStrategyFactory.getStrategy("str");
        System.err.println(messageStrategy);
         Map<String, Object> map = new HashMap<>();
        map.put("12","新消息");
        try {
            messageStrategy.sendMsg(map,"1001");
        }catch (Exception e){
            throw new RuntimeException();
        }
        System.err.println("定时发送中");
    }





}
